import { Application } from 'pixi.js';
import AudioManager from './audio.js';
import ListenerManager from './listener.js';
import LoadingManager from './loading.js';
import EventManager from './event.js';
import { createSpriteManager, loadAllSpriteResources } from './sprites/index.js';

class GameStage {
    constructor() {
        this.appWidth = 640;
        this.appHeight = 640;
        this.scale = 1.0;
        this.app = new Application();
        this.loadingManager = new LoadingManager();
        this.listenerManager = new ListenerManager();
        this.eventManager = EventManager;
        this.spriteManager = null;
    }

    async init(container) {
        this.loadingManager.setGameState('loading');

        await this.app.init({
            background: '#0e52b4',
            width: this.appWidth * this.scale,
            height: this.appHeight * this.scale,
        });

        this.app.stage.scale.set(this.scale);

        container.appendChild(this.app.canvas);

        await this.loadAllResources();
        this.spriteManager = await createSpriteManager(this.app);
        this.loadingManager.setGameState('ready');
    }

    async startGame() {
        this.startGameLoop();
    }

    async loadAllResources() {
        console.log('开始加载资源...');
        await Promise.all([
            this.loadFonts(),
            this.loadAudioResources(), 
            this.loadSpriteResources()
        ]);
        
        console.log('所有资源加载完成');
    }

    async loadFonts() {
        try {
            await document.fonts.load('48px MyFont');
            console.log('字体加载完成');
        } catch (error) {
            console.error('字体加载失败:', error);
        }
    }

    async loadAudioResources() {
        await AudioManager.loadAll();
        console.log('音频资源加载完成');
    }

    async loadSpriteResources() {
        await loadAllSpriteResources();
        console.log('精灵资源加载完成');
    }

    startGameLoop() {
        this.app.ticker.add((time) => {
            if (this.spriteManager) {
                this.spriteManager.updateAll(time.deltaTime);
            }
        });
    }

    setScale(newScale) {
        if (newScale <= 0) return;
        this.scale = newScale;
        if (this.app && this.app.stage) {
            this.app.stage.scale.set(this.scale);
        }
    }

    getScale() {
        return this.scale;
    }

    getSprite(name) {
        return this.spriteManager?.get(name);
    }

    getSpriteStats() {
        return this.spriteManager?.getStats();
    }

    destroy() {
        if (this.spriteManager) {
            this.spriteManager.destroy();
        }
        this.listenerManager.destroy();
        AudioManager.destroy();
        
        if (this.app) {
            this.app.destroy(true);
        }
    }
}

export default new GameStage();
